import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Row, Col, Card, Form, Input, Select, Button, Popconfirm, Modal, message, InputNumber, Upload, Icon } from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { imgPrex } from '../../utils/constData';

import styles from './Channel.less';

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible, title, record, normFile, loading, fileList, _this } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      handleAdd(fieldsValue, form);
      // form.resetFields();
    });
  };

  const onCancel = () => {
    // form.resetFields();
    handleModalVisible(false, null, form);
  };

  const uploadProps = {
    onRemove: (file) => {
      _this.setState(({ fileList }) => {
        const index = fileList.indexOf(file);
        const newFileList = fileList.slice();
        newFileList.splice(index, 1);
        return {
          fileList: newFileList,
          file: null,
        };
      });
      form.setFieldsValue({ name: (record && record.channelImg) ? record.channelImg : null })
    },

    beforeUpload: (file) => {
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (!isLt1M) {
        message.error('图片大小不能超过1M');
        return false;
      }
      _this.setState(({ fileList }) => ({
        fileList: [file],
        file: file,
        image: null,
      }));
      form.setFieldsValue({
        name: file
      });
      return false;
    },
    fileList: fileList
  };


  return (
    <Modal
      title={record ? "编辑频道" : '添加频道'}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={onCancel}
      confirmLoading={true}
      footer={[
        <Button key="取消" onClick={onCancel}>取消</Button>,
        <Button key="submit" type="primary" loading={loading} onClick={okHandle}>
          确定
        </Button>,
      ]}
    >
      {
        record ?
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="id" style={{ display: 'none' }}>
            {form.getFieldDecorator('channelId', {
              initialValue: record ? ('' + record.channelId) : '',
              // rules: [{ required: true, message: 'id' }],
            })(
              <Input hidden={true} placeholder="channelId" />
            )}
          </FormItem>
          :
          null
      }
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="所属APP">
        {form.getFieldDecorator('appType', {
          initialValue: record ? ('' + record.appType) : '1',
          rules: [{ required: true, message: '请选择所属App' }],
        })(
          <Select style={{ width: '60%' }}>
            <Option value="1">小萌早教</Option>
            <Option value="2">小萌绘本</Option>
            <Option value="3">萌萌乐卡通</Option>
            <Option value="4">萌萌乐儿歌</Option>
          </Select>
        )}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="频道名称">
        {form.getFieldDecorator('channelName', {
          initialValue: record ? record.channelName : null,
          rules: [{ required: true, message: '名称不能为空或特殊字符',
          pattern: /^[A-Za-z0-9\u4e00-\u9fa5-]*$/
           }],
        })(<Input placeholder="请输入频道名称" maxLength="30" />)}
      </FormItem>

      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="频道图标">
        {
          form.getFieldDecorator('name', {
            valuePropName: 'file',
            getValueFromEvent: normFile,
            rules: [{ required: true, message: '请选择频道图标' }],
            initialValue: record ? record.channelImg : null,
          })
            (<Upload
              {...uploadProps}
            >
              <Button>
                <Icon type="upload" />浏览
         			  </Button>
            </Upload>)}
        {(record && record.channelImg && !(fileList && (fileList.length > 0))) ?
          <img src={imgPrex + record.channelImg} style={{ width: 50 }} />
          :
          null
        }
      </FormItem>

      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="权重">
        {form.getFieldDecorator('weight', {
          initialValue: record ? record.weight : null,
          rules: [{ required: true, message: '请输入频道权重'         }],
        })(<InputNumber placeholder="请输入频道权重" maxLength="10" style={{ width: '100%' }} />)}
      </FormItem>
    </Modal>
  );
});

@connect(({ channel, loading }) => ({
  channel,
  channelList: channel.channelList,
  pagination: channel.pagination,
  loading: loading.models.channel,
}))
@Form.create()
export default class Channel extends PureComponent {
  state = {
    modalVisible: false,
    selectedRows: [],
    formValues: {},
    record: null,

    fileList: [],
    file: null,
    image: null,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'channel/fetchChannelList',
      payload: { appType: 1, pageNum: 1, pageSize: 10 }
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      ...this.props.form.getFieldsValue(),
    };

    dispatch({
      type: 'channel/fetchChannelList',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    const params = { pageNum: 1, pageSize: 10, };
    dispatch({
      type: 'channel/fetchChannelList',
      payload: { appType: 1, pageNum: 1, pageSize: 10 }
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch() {
    const params = {
      pageNum: 1,
      pageSize: 10,
      ...this.props.form.getFieldsValue(),
    };
    this.props.dispatch({
      type: 'channel/fetchChannelList',
      payload: params,
    });
  }

  handleModalVisible(flag, record, form) {
    if (!flag) {
      if (form) {
        form.resetFields();
      }

      // this.props.form.resetFields();

      this.setState({
        modalVisible: false,
        record: null,
        fileList: [],
        file: null,
        image: null,
      });
    } else {
      console.log('模态框打开------', record)
      this.setState({
        modalVisible: true,
        record: record ? record : null,
        image: record ? record.channelImg : null,
      });
    }
  };

  handleAdd(fieldsValue, form) {
    console.log('表单数据fieldsValue?????', fieldsValue)

    let values = {};
    if (this.state.file) {
      values = {
        ...fieldsValue,
        'name': this.state.file,
      }
    } else {
      values = {
        ...fieldsValue,
        'name': undefined,
      }
    }

    console.log('valuesvaluesvalues?????', values)

    const { dispatch } = this.props;
    if (values.channelId) {
      dispatch({
        type: 'channel/updateChannel',
        payload: values,
        callback: () => this.callback('update', form)
      });
    } else {
      dispatch({
        type: 'channel/addChannel',
        payload: values,
        callback: () => this.callback('add', form)
      });
    }
  };

  callback(type, form) {
    if (type == 'delete') {
      this.setState({ selectedRows: [] });
      this.handleSearch();
    } else {
      this.handleModalVisible(false, null, form)
      this.handleSearch();
    }
  }

  normFile = (e) => {
    const isLt1M = e.file.size / 1024 / 1024 < 1;
    if (!isLt1M) {
      this.setState({ fileList: [], file: null })
      return (this.state.record && this.state.record.channelImg) ? this.state.record.channelImg : null;
    }

    if (e.fileList && e.fileList.length > 0) {
      return e && e.file;
    } else {
      return null;
    }
  }

  renderSimpleForm() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="所属App">
              {getFieldDecorator('appType', { initialValue: '1' })(
                <Select style={{ width: '100%' }}>
                  <Option value="1">小萌早教</Option>
                  <Option value="2">小萌绘本</Option>
                  <Option value="3">萌萌乐卡通</Option>
                  <Option value="4">萌萌儿歌</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="频道名称">
              {getFieldDecorator('channelName')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" onClick={() => this.handleSearch()}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  _delete(selectedRows) {

    if (selectedRows && selectedRows.length > 0) {
      let recordList = [];
      for (let i in selectedRows) {
        let one = { channelId: selectedRows[i].channelId }
        recordList.push(one)
      }

      if (recordList) {
        this.props.dispatch({
          type: 'channel/deleteChannel',
          payload: { channelList: recordList },
          callback: () => this.callback('delete')
        });
      }
    } else {
      message.error('请选择内容')
    }
  }

  render() {
    const {
      channelList,
      pagination,
      loading,
    } = this.props;
    const { selectedRows, modalVisible } = this.state;

    const tableData = {}
    tableData['list'] = channelList;
    tableData['pagination'] = pagination;
    console.log('tableDatatableDatatableData:', tableData)

    const columns = [
      {
        title: '频道名称',
        dataIndex: 'channelName',
        key: 'channelName',
      },
      {
        title: '所属App',
        dataIndex: 'appType',
        key: 'app',
        render(text, record) {
          return <span>{text == '1' ? '小萌早教' : text == '2' ? '小萌绘本' : text == '3' ? '萌萌乐视频' : text == '4' ? '萌萌乐儿歌' : '其他'}</span>;
        },
      },
      {
        title: '图标',
        dataIndex: 'channelImg',
        key: 'channelImg',
        render(text, record) {
          return <img src={imgPrex + text} style={{ width: 30, height: 30 }} />;
        },
      },
      {
        title: '权重',
        dataIndex: 'weight',
        key: 'weight',
      },
      {
        title: '操作',
        render: (text, record) => (
          <Fragment>
            <a onClick={() => this.handleModalVisible(true, record)}>编辑</a>
          </Fragment>
        ),
      },
    ];

    const parentMethods = {
      handleAdd: (fields, form) => this.handleAdd(fields, form),
      handleModalVisible: (flag, record, form) => this.handleModalVisible(flag, record, form),
    };



    return (
      <PageHeaderLayout title="">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                添加
              </Button>
              {selectedRows.length > 0 && (
                <span>
                  <Popconfirm title="确定要删除选中的频道吗?" placement="bottom" onConfirm={() => this._delete(selectedRows)} onCancel={() => { }} okText="确定" cancelText="取消">
                    <Button type="danger" icon="delete" >
                      删除
                  </Button>
                  </Popconfirm>
                </span>
              )}
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={tableData}
              rowKey="channelId"
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible} record={this.state.record}
          loading={loading} image={this.state.image} normFile={(e) => this.normFile(e)} _this={this}
          fileList={this.state.fileList}
        />
      </PageHeaderLayout>
    );
  }
}
